package com.xm.controller;

import com.xm.common.pojo.JsonResult;
import com.xm.common.util.PageUtil;
import com.xm.pojo.User;
import com.xm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RequestMapping("/user/")
@RestController
public class UserController {
    @Autowired
    UserService userService;



    @PostMapping
    JsonResult doSaveUser(@RequestBody User user){
            userService.saveUser(user);
            return new JsonResult("save ok");


    }

    @DeleteMapping("{id}")
    JsonResult doDeleteUser(@PathVariable Integer id){
            userService.deleteById(id);
            return new JsonResult("delete ok");

    }

    @PutMapping
    public JsonResult doUpdateUser(@RequestBody User user){
            userService.updateUser(user);
            return new JsonResult("update ok");
    }



    @GetMapping("login/{username}/{password}")
    public JsonResult login(@PathVariable String username,
                            @PathVariable String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        token.setRememberMe(true);
        subject.login(token);
        return new JsonResult("登录ok");

    }

    @GetMapping
    JsonResult doFindUser(User user){
        return new JsonResult(PageUtil.startPage().doSelectPageInfo(
                ()-> userService.findUser(user)
        ));

    }



    @GetMapping("{id}")
    public JsonResult doFindById(@PathVariable Integer id){
        return new JsonResult(userService.findById(id));
    }
}
